<template>
  <div class="setup-phone-container">
    <el-card>
      <el-form
        ref="phoneFormRef"
        :model="phoneForm"
        :rules="phoneRules"
        label-width="100px"
        class="phone-form"
      >
        <el-form-item
          v-if="Number(privacyTimeValue) === 0"
          label="旧手机号"
        >
          <el-input
            disabled
            :model-value="hidden(phoneForm.oldPhone, 3, 4)"
            placeholder="请输入旧手机号"
          />
        </el-form-item>
        <el-form-item
          v-else
          label="旧手机号"
          prop="oldPhone"
        >
          <el-input
            v-model="phoneForm.oldPhone"
            disabled
            placeholder="请输入旧手机号"
          />
        </el-form-item>
        <el-form-item label="新手机号" prop="newPhone">
          <el-input
            v-model="phoneForm.newPhone"
            maxlength="11"
            placeholder="请输入新手机号"
          />
        </el-form-item>
        <el-form-item label="验证码" prop="code">
          <el-input
            v-model="phoneForm.code"
            maxlength="6"
            placeholder="请输入验证码"
          >
            <template #append>
              <el-button
                class="code-btn"
                type="primary"
                :loading="codeLoading"
                :disabled="codeDisabled"
                @click="getCode"
              >
                <span v-if="!codeLoading && !countdownValue">{{ codeButtonText }}</span>
                <span v-else-if="codeLoading">发送中...</span>
                <span v-else>{{ countdownValue }}s</span>
              </el-button>
            </template>
          </el-input>
        </el-form-item>
        <el-form-item>
          <el-button
            type="primary"
            :loading="submitLoading"
            @click="submitForm"
          >
            确定
          </el-button>
        </el-form-item>
      </el-form>
    </el-card>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted, computed, onUnmounted } from 'vue'
import { ElMessage, FormInstance } from 'element-plus'
import { PhoneService } from '@/api/setupApi'
import { UserUpdatePhoneParam } from '@/api/model/setupModel'
import { ApiStatus } from '@/utils/http/status'

const TIME_COUNT = 120 // 更改倒计时时间

// 表单引用
const phoneFormRef = ref<FormInstance>()

// 数据状态
const submitLoading = ref(false)
const codeLoading = ref(false)
const countdownValue = ref(0)
const privacyTimeValue = ref(0)
const timer = ref<NodeJS.Timeout | null>(null)

// 手机号表单
const phoneForm = reactive({
  oldPhone: '',
  newPhone: '',
  code: ''
})

// 表单验证规则
const phoneRules = {
  oldPhone: [
    { required: true, message: '请输入旧手机号', trigger: 'blur' },
    { pattern: /^1[3456789]\d{9}$/, message: '请输入正确的手机号', trigger: 'blur' }
  ],
  newPhone: [
    { required: true, message: '请输入新手机号', trigger: 'blur' },
    { pattern: /^1[3456789]\d{9}$/, message: '请输入正确的手机号', trigger: 'blur' }
  ],
  code: [
    { required: true, message: '请输入验证码', trigger: 'blur' }
  ]
}

// 计算验证码按钮是否禁用
const codeDisabled = computed(() => {
  return !phoneForm.newPhone || countdownValue.value > 0
})

// 计算验证码按钮文本
const codeButtonText = computed(() => {
  return countdownValue.value > 0 ? `${countdownValue.value}s后重新发送` : '获取验证码'
})

// 获取管理员电话
const getPhone = async () => {
  try {
    const res = await PhoneService.getAdminPhone()
    if (res.code === ApiStatus.success) {
      phoneForm.oldPhone = res.data || ''
    } else {
      ElMessage.error(res.message || '获取旧手机号失败')
    }
  } catch (error) {
    console.error('获取旧手机号异常:', error)
    ElMessage.error('获取旧手机号失败')
  }
}

// 获取验证码
const getCode = async () => {
  if (!phoneForm.newPhone) {
    ElMessage.error('请填写新手机号')
    return
  }

  if (!/^1[3456789]\d{9}$/.test(phoneForm.newPhone)) {
    ElMessage.error('请填写正确手机号')
    return false
  }

  if (countdownValue.value > 0) return

  codeLoading.value = true

  try {
    const res = await PhoneService.getUpdatePhoneCode(phoneForm.newPhone)
    if (res.code === ApiStatus.success) {
      ElMessage.success('发送成功，请注意查看手机短信')

      // 启动倒计时
      countdownValue.value = 60
      if (timer.value) clearInterval(timer.value)
      timer.value = setInterval(() => {
        countdownValue.value--
        if (countdownValue.value <= 0 && timer.value) {
          clearInterval(timer.value)
          timer.value = null
        }
      }, 1000)
    } else {
      ElMessage.error(res.message || '发送验证码失败')
    }
  } catch (error) {
    console.error('发送验证码异常:', error)
    ElMessage.error('发送验证码失败')
  } finally {
    codeLoading.value = false
  }
}

// 提交手机号修改
const submitForm = async () => {
  if (!phoneFormRef.value) return

  await phoneFormRef.value.validate(async (valid) => {
    if (valid) {
      submitLoading.value = true

      try {
        const param: UserUpdatePhoneParam = {
          phone: phoneForm.newPhone,
          code: phoneForm.code
        }

        const res = await PhoneService.updatePhone(param)
        if (res.code === ApiStatus.success) {
          ElMessage.success('手机号修改成功')
          getPhone() // 重新获取手机号
          // 重置表单
          phoneForm.newPhone = ''
          phoneForm.code = ''
        } else {
          ElMessage.error(res.message || '手机号修改失败')
        }
      } catch (error) {
        console.error('手机号修改异常:', error)
        ElMessage.error('手机号修改失败')
      } finally {
        submitLoading.value = false
      }
    }
  })
}

// 中间部分隐藏手机号
const hidden = (str: string, frontLen: number, endLen: number) => {
  if (!str) return ''

  let endLenData = 0
  if (str.length !== 2) {
    endLenData = endLen
  }
  const len = str.length - frontLen - endLenData
  let xing = ''
  for (let i = 0; i < len; i++) {
    xing += '*'
  }
  return (
    str.substring(0, frontLen) +
    xing +
    str.substring(str.length - endLenData)
  )
}

// 初始化
onMounted(() => {
  getPhone()
  privacyTimeValue.value = parseInt(localStorage.getItem('privacyTime') || '0')
})

// 组件销毁时清理定时器
onUnmounted(() => {
  if (timer.value) {
    clearInterval(timer.value)
  }
})
</script>

<style scoped lang="scss">
.setup-phone-container {
  padding: 20px;

  .phone-form {
    width: 600px;
    margin: 0 auto;

    .el-form-item__label {
      font-weight: bold;
    }

    .el-input {
      width: 70%;

      :deep(.el-input__inner) {
        height: 38px;
      }
    }

    .el-button {
      height: 38px;
    }

    .code-btn {
      height: 38px;
    }
  }
}

// 响应式设计 - IPad Pro
@media screen and (max-width: $device-ipad-pro) {
  .setup-phone-container {
    padding: 15px;

    .phone-form {
      width: 100%;
    }
  }
}

// 响应式设计 - IPad 竖屏
@media screen and (max-width: $device-ipad-vertical) {
  .setup-phone-container {
    padding: 15px;
  }
}

// 响应式设计 - IPad
@media screen and (max-width: $device-ipad) {
  .setup-phone-container {
    padding: 15px;
  }
}

// 响应式设计 - 手机
@media screen and (max-width: $device-phone) {
  .setup-phone-container {
    padding: 10px;

    .phone-form {
      width: 100%;

      .el-input {
        width: 100%;
      }

      .el-form-item__label {
        width: 80px !important;
      }
    }
  }
}
</style>
